package cn.com.zsc.loginFiter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends HttpServlet implements Filter {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * filterConfig
	 */
	private FilterConfig filterConfig;

	/**
	 * 初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	/**
	 * 处理请求响应
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) {
		try {
			request.setCharacterEncoding("UTF-8");
			
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;

			// 获取请求的URI
			String uriStr = httpRequest.getRequestURI();
			
			// 获取不包含的字符串
			String[] unIncludeStrings = filterConfig.getInitParameter("unIncludeStrings").split(";");

			// 如果没有登录且访问的不是登录页面
			if (httpRequest.getSession().getAttribute("user") == null
					&& !isContains(uriStr, unIncludeStrings)) {
				httpResponse.sendRedirect(httpRequest.getContextPath()+"/login.jsp");
			} else {
				filterChain.doFilter(request, response);
			}
		} catch (ServletException sx) {
			filterConfig.getServletContext().log(sx.getMessage());
		} catch (IOException iox) {
			filterConfig.getServletContext().log(iox.getMessage());
		}
	}
	
	/**
	 * 是否包含指定字符串
	 * @param container
	 * @param regx
	 * @return
	 */
	public boolean isContains(String container, String[] regx) {
        boolean result = false;
        
        for (int i = 0; i < regx.length; i++) {
              if (container.indexOf(regx[i]) != -1) {
                    return true;
              }
        }
        
        return result;
	}

	public void destroy() {
	}
}
